package com.shenzhen.horselive.base;

import android.app.Dialog;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.shenzhen.horselive.R;

import butterknife.ButterKnife;
import butterknife.Unbinder;


//
//onAttach
//onCreate
//onCreateDialog
//setupDialog
//onCreateView
//onViewCreated
//onActivityCreated
//onStart
// onStop
//onDestroyView
//onDestroy
//onDetach
public abstract class BaseDialogFragment extends DialogFragment {

    private boolean mFinishInflate = false;
    private LayoutInflater mInflater;
    protected View mLayoutView;
    Unbinder unbinder;
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getActivity(), R.style.CommonDialog);
        dialog.setCanceledOnTouchOutside(true);
        return dialog;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mLayoutView == null) {
            mLayoutView = inflate(inflater);
            onInflateView(mLayoutView);
            onPrepareData();
            mFinishInflate = true;
        } else {
            ViewGroup parent = (ViewGroup) mLayoutView.getParent();
            if (parent != null)
                parent.removeView(mLayoutView);
            onRefreshData();
        }
        mInflater = inflater;
        return mLayoutView;


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
            unbinder = null;
        }
    }

    protected View inflate(LayoutInflater inflater) {
        return inflater.inflate(getContentViewId(), null);
    }

    protected abstract int getContentViewId();

    /**
     * 只运行一次
     */
    public void onInflateView(View contentView) {
        unbinder = ButterKnife.bind(this, contentView);
    }

    /**
     * 只运行一次
     */
    public void onPrepareData() {
    }

    public void onRefreshData() {

    }

    public boolean isFinishInflate() {
        return mFinishInflate;
    }

    protected LayoutInflater getInflater() {
        return mInflater;
    }

    public void show(FragmentManager manager) {
        if(!isAdded()) {
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, getClass().getName());
            ft.commitAllowingStateLoss();
        }
    }
}